// pages/order/hotel/hotel.js
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    orderDetail: null,
    isLoading: true,
    // 新增酒店预订相关数据
    roomId: null,
    hotelId: null,
    room: null,
    hotel: null,
    quantity: 1,
    checkInDate: '',
    checkOutDate: '',
    nights: 1,
    totalAmount: '0.00',
    isOrderDetail: false, // 标记是订单详情还是预订页面
    statusColorMap: {
      1: '#ff6b6b', // 待支付
      2: '#4b7bec', // 已支付
      3: '#4b7bec', // 已完成
      4: '#999999'  // 已取消
    },
    statusTextMap: {
      1: '待支付',
      2: '已支付',
      3: '已完成',
      4: '已取消'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options && options.id) {
      // 订单详情模式
      this.setData({
        orderId: options.id,
        isOrderDetail: true
      });
      this.fetchOrderDetail(options.id);
      
      // 设置导航栏
      wx.setNavigationBarTitle({
        title: '酒店订单详情'
      });
    } else if (options && options.roomId && options.hotelId) {
      // 预订模式
      this.setData({
        roomId: parseInt(options.roomId),
        hotelId: parseInt(options.hotelId),
        isOrderDetail: false
      });
      
      // 设置导航栏
      wx.setNavigationBarTitle({
        title: '酒店预订'
      });
      
      // 设置默认入住日期为明天
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      
      // 设置默认离店日期为后天
      const dayAfterTomorrow = new Date();
      dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2);
      
      this.setData({
        checkInDate: this.formatDate(tomorrow),
        checkOutDate: this.formatDate(dayAfterTomorrow)
      });
      
      // 加载酒店和房间信息
      this.loadHotelAndRoom();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  /**
   * 加载酒店和房间信息
   */
  loadHotelAndRoom() {
    wx.showLoading({
      title: '加载中',
    });
    
    // 获取酒店信息
    wx.mRequest({
      url: `/api/hotel/${this.data.hotelId}`,
      method: 'GET',
      success: (res) => {
        if (res.code === 0 && res.data) {
          const hotel = res.data;
          
          // 找到选中的房间
          const room = hotel.rooms.find(r => r.id === this.data.roomId);
          
          if (room) {
            this.setData({
              hotel: hotel,
              room: room,
              isLoading: false
            });
            
            // 计算初始总价
            this.calculateTotal();
          } else {
            wx.showToast({
              title: '未找到选中的房间',
              icon: 'none'
            });
            setTimeout(() => {
              wx.navigateBack();
            }, 1500);
          }
        } else {
          wx.showToast({
            title: '加载酒店信息失败',
            icon: 'none'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
        
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('获取酒店信息失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    });
  },
  
  /**
   * 计算总价
   */
  calculateTotal() {
    if (this.data.room && this.data.room.price) {
      const nights = this.calculateNights(this.data.checkInDate, this.data.checkOutDate);
      const total = (this.data.room.price * this.data.quantity * nights).toFixed(2);
      
      this.setData({
        nights: nights,
        totalAmount: total
      });
    }
  },
  
  /**
   * 计算入住晚数
   */
  calculateNights(checkInDate, checkOutDate) {
    const start = new Date(checkInDate);
    const end = new Date(checkOutDate);
    const diffTime = Math.abs(end - start);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  },
  
  /**
   * 格式化日期
   */
  formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  
  /**
   * 入住日期选择
   */
  bindCheckInDateChange(e) {
    const checkInDate = e.detail.value;
    let { checkOutDate } = this.data;
    
    // 确保离店日期不早于入住日期
    if (new Date(checkOutDate) <= new Date(checkInDate)) {
      const nextDay = new Date(checkInDate);
      nextDay.setDate(nextDay.getDate() + 1);
      checkOutDate = this.formatDate(nextDay);
    }
    
    this.setData({
      checkInDate,
      checkOutDate
    }, () => {
      this.calculateTotal();
    });
  },
  
  /**
   * 离店日期选择
   */
  bindCheckOutDateChange(e) {
    this.setData({
      checkOutDate: e.detail.value
    }, () => {
      this.calculateTotal();
    });
  },
  
  /**
   * 数量减少
   */
  decreaseQuantity() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      }, () => {
        this.calculateTotal();
      });
    }
  },
  
  /**
   * 数量增加
   */
  increaseQuantity() {
    if (this.data.quantity < this.data.room.available) {
      this.setData({
        quantity: this.data.quantity + 1
      }, () => {
        this.calculateTotal();
      });
    } else {
      wx.showToast({
        title: '已达最大可预订数量',
        icon: 'none'
      });
    }
  },
  
  /**
   * 提交酒店订单
   */
  submitOrder() {
    // 检查登录状态
    if (!app.checkLogin()) {
      wx.showModal({
        title: '提示',
        content: '请先登录再提交订单',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }
    
    // 获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo.userId) {
      wx.showToast({
        title: '用户信息不完整，请重新登录',
        icon: 'none'
      });
      return;
    }
    
    // 校验数据
    if (!this.data.room) {
      wx.showToast({
        title: '房间信息不存在',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.checkInDate || !this.data.checkOutDate) {
      wx.showToast({
        title: '请选择入住和离店日期',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载
    wx.showLoading({
      title: '提交订单中...',
    });
    
    // 准备订单数据
    const orderData = {
      user: { id: userInfo.userId },
      productId: this.data.room.id,
      type: 2,  // 2-酒店订单
      quantity: this.data.quantity,
      totalAmount: this.data.totalAmount,
      bookDate: this.formatDate(new Date()),
      useDate: this.data.checkInDate,
      endDate: this.data.checkOutDate,
      status: 1  // 1-待支付
    };
    
    console.log('创建酒店订单数据:', orderData);
    
    // 调用创建订单API
    wx.mRequest({
      url: '/api/order/create',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: orderData,
      success: (res) => {
        wx.hideLoading();
        console.log('创建订单响应:', res);
        
        if (res.code === 0) {
          wx.showToast({
            title: '预订成功',
            icon: 'success',
            duration: 2000
          });
          
          // 跳转到订单详情页
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/order/order?tab=1'  // 1-待支付
            });
          }, 2000);
        } else {
          wx.showToast({
            title: res.msg || '预订失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('创建订单失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 获取订单详情
   */
  fetchOrderDetail(orderId) {
    const _this = this;
    // 显示加载中
    wx.showLoading({
      title: '加载中',
    });

    // 调用真实API获取订单详情
    wx.mRequest({
      url: `/api/order/${orderId}`,
      method: 'GET',
      success: (res) => {
        wx.hideLoading();
        
        if (res.code === 0 && res.data) {
          console.log('订单详情响应:', res.data);
          
          // 处理订单状态文本
          let statusText = '';
          switch(res.data.status) {
            case 1: statusText = '待支付'; break;
            case 2: statusText = '已支付'; break;
            case 3: statusText = '已完成'; break;
            case 4: statusText = '已取消'; break;
            default: statusText = '未知状态';
          }
          
          // 补充默认图片
          if (!res.data.image) {
            res.data.image = '/img/logo.png';
          }
          
          _this.setData({
            orderDetail: res.data,
            isLoading: false
          });
        } else {
          wx.showToast({
            title: res.msg || '获取订单详情失败',
            icon: 'none'
          });
          _this.setData({
            isLoading: false
          });
        }
      },
      fail: (err) => {
        console.error('获取订单详情失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
        _this.setData({
          isLoading: false
        });
      }
    });
  },

  /**
   * 支付订单
   */
  payOrder() {
    wx.showModal({
      title: '确认支付',
      content: '确认支付此订单吗？',
      confirmColor: '#4b7bec',
      success: (res) => {
        if (res.confirm) {
          // 显示加载中
          wx.showLoading({
            title: '处理中...',
          });
          
          // 调用支付API
          wx.mRequest({
            url: '/api/payment/pay',
            method: 'POST',
            data: {
              orderId: parseInt(this.data.orderId),
              method: 1  // 1-微信支付
            },
            success: (res) => {
              wx.hideLoading();
              
              if (res.code === 0) {
                wx.showToast({
                  title: '支付成功',
                  icon: 'success'
                });
                
                // 刷新订单详情
                setTimeout(() => {
                  this.fetchOrderDetail(this.data.orderId);
                }, 1500);
              } else {
                wx.showToast({
                  title: res.msg || '支付失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.hideLoading();
              wx.showToast({
                title: '支付失败，请重试',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 取消订单
   */
  cancelOrder() {
    wx.showModal({
      title: '确认取消',
      content: '确定要取消此订单吗？',
      confirmColor: '#ff6b6b',
      success: (res) => {
        if (res.confirm) {
          // 显示加载中
          wx.showLoading({
            title: '处理中...',
          });
          
          // 调用取消订单API
          wx.mRequest({
            url: `/api/order/${this.data.orderId}/cancel`,
            method: 'PUT',
            success: (res) => {
              wx.hideLoading();
              
              if (res.code === 0) {
                wx.showToast({
                  title: '订单已取消',
                  icon: 'success'
                });
                
                // 刷新订单详情
                setTimeout(() => {
                  this.fetchOrderDetail(this.data.orderId);
                }, 1500);
              } else {
                wx.showToast({
                  title: res.msg || '取消失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.hideLoading();
              wx.showToast({
                title: '取消失败，请重试',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  }
})